package com.crm.sys.handler;

import java.net.InetAddress;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crm.im.core.constant.IMConstant;
import com.crm.im.core.handler.IMRequestHandler;
import com.crm.im.core.model.Message;
import com.crm.im.core.model.ReplyBody;
import com.crm.im.core.model.SentBody;
import com.crm.im.core.session.DefaultSessionManager;
import com.crm.im.core.session.IMSession;
import com.crm.sys.push.DefaultMessagePusher;
import com.crm.sys.push.SystemMessagePusher;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.StringUtil;
 

/**
 * 账号绑定实现
 * 
 */ 
@Service("bindHandler")
public class BindHandler implements IMRequestHandler {

	protected final Logger logger = Logger.getLogger(BindHandler.class);
	@Autowired
	private DefaultSessionManager sessionManager;
	@Autowired
	private SystemMessagePusher systemMessagePusher;
	@Autowired
	private UserService userService;
	
	
	public ReplyBody process(IMSession newSession, SentBody message) {
		ReplyBody reply = new ReplyBody();
		reply.setCode(IMConstant.ReturnCode.CODE_200);
		try { 
			
			String account = message.get("account");
			UserInfo  info = userService.getUserInfo(Long.parseLong(account));
			
			newSession.setGid(StringUtil.getUUID());
			newSession.setAccount(account);
			//newSession.setName(message.get("name"));
			newSession.setName(info.getName());
			newSession.setPhotoUrl(message.get("photoUrl"));
			newSession.setDeviceId(message.get("deviceId"));
			newSession.setHost(InetAddress.getLocalHost().getHostAddress());
			newSession.setChannel( message.get("channel"));
			newSession.setDeviceModel(message.get("device"));
			newSession.setClientVersion(message.get("version"));
			newSession.setSystemVersion(message.get("osVersion"));
			newSession.setBindTime(System.currentTimeMillis());
			newSession.setPackageName(message.get("packageName"));
			/**
			 * 由于客户端断线服务端可能会无法获知的情况，客户端重连时，需要关闭旧的连接
			 */
			IMSession oldSession  = sessionManager.get(account);
				
			//如果是账号已经在另一台终端登录。则让另一个终端下线
			if(oldSession!=null)
			{
				if(oldSession.fromOtherDevice(newSession))
				{
					sendForceOfflineMessage(oldSession,account);
				}
				
				if(oldSession.equals(newSession))
				{
					reply.put("sid", oldSession.getGid());
					return reply;
				}
				
				oldSession.removeAttribute(IMConstant.SESSION_KEY);
				oldSession.closeNow();
			}
			
			
			//第一次设置心跳时间为登录时间
			newSession.setBindTime(System.currentTimeMillis());
			newSession.setHeartbeat(System.currentTimeMillis());
			
			  if(!account.equals(1)){
				//通知上线消息
				List<IMSession>  sessionList = sessionManager.queryAll();
				for(IMSession s:sessionList){
					Message  msg = new Message();
					msg.setType(IMConstant.MessageType.TYPE_ONLINE);//强行下线消息类型
					msg.setReceiver(s.getAccount());
					msg.setContent(account);
					systemMessagePusher.push(msg); 
				}
			  }
				
			sessionManager.add(account, newSession);
			
		} catch (Exception e) {
			reply.setCode(IMConstant.ReturnCode.CODE_500);
			e.printStackTrace();
		}
		logger.debug("bind :account:" +message.get("account")+"------name:" +message.get("name")+"-----------------------" +reply.getCode());
		reply.put("sid", newSession.getGid());
		return reply;
	}
	
	
	
	private void sendForceOfflineMessage(IMSession oldSession,String account){
		
		Message  msg = new Message();
		msg.setType(IMConstant.MessageType.TYPE_999);//强行下线消息类型
		msg.setReceiver(account);
		
		if(oldSession.isLocalhost() && oldSession.isConnected())
		{
			oldSession.write(msg);
			oldSession.closeOnFlush();
		}
		if(!oldSession.isLocalhost())
		{
			systemMessagePusher.push(msg);
		}
		oldSession.removeAttribute(IMConstant.SESSION_KEY);
		
	}
	
}